package ifmo.compiler.task21.lexer;

import ifmo.compiler.task21.lexer.tokens.Token;
import ifmo.compiler.task21.lexer.tokens.TokenType;
import ifmo.compiler.task21.lexer.tokens.WrongTokenException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * The lexer
 *
 * @author byaminov
 */
public class Lexer {

    private LexerAutomaton automaton;

    private List<TokenType> ignoredTokens;

    public Lexer(InputStream program) {
        if (program == null) {
            throw new IllegalArgumentException("Program input stream must not be null");
        }
        this.automaton = new LexerAutomaton(program);

        ignoredTokens = new ArrayList<TokenType>();
        ignoredTokens.add(TokenType.WS);
        //ignoredTokens.add(TokenType.LINE_COMMENT);
    }

    public List<TokenType> getIgnoredTokens() {
        return ignoredTokens;
    }

    public Token nextToken() throws WrongTokenException {
        try {
            Token token = automaton.nextToken();
            if (!ignoredTokens.contains(token.getType())) {
                return token;
            } else {
                return nextToken();
            }
        } catch (IOException e) {
            throw new WrongTokenException("Could not get token due to IOException", e);
        }
    }

    /* Test on example */
    public static void main(String[] args) {
        try {
            Lexer lexer = new Lexer(new FileInputStream("examples/Example1.java"));
            // String program = "a+b >= c while bb/b = 1.0 and g == 2/5 or comon < 3;";
            // Lexer lexer = new Lexer(new ByteArrayInputStream(program.getBytes()));

            Token token;
            do {
                token = lexer.nextToken();
                System.out.println(token.getType() + ": " + token);
            } while (token.getType() != TokenType.END);
        } catch (FileNotFoundException e) {
            System.out.println("Could not find file: " + e);
        } catch (WrongTokenException e) {
            System.out.println("Wrong token: " + e);
        }
    }

}
